<template>
  <div>
    <div class="wrapper">
      <Anchor :labelList="labels" :labelWidth="85">
        <div id="row-01" class="line">
          <BreakSpace label="基本信息" :containerStyle="{ marginTop: '10px', marginBottom: '10px' }"></BreakSpace>
          <FormPanel ref="formPanel" :list="formList" labelWidth="130" :cols="3" :formType="type" :isSubmitBtn="false" @formChange="formChangeHandle" />
        </div>
        <div id="row-02" class="line">
          <BreakSpace label="装饰件信息" :containerStyle="{ marginTop: '10px', marginBottom: '10px' }"></BreakSpace>
          <FilterTable
            ref="table1"
            columnsRef="ygzsj1"
            :columns="columnsWts"
            :dataSource="listWts"
            selectionType="multiple"
            :onRowSelectChange="handlePartTableSelectChange"
            :onColumnsChange="columns => (this.columnsWts = columns)"
          >
            <template slot="moreActions">
              <span @click="removeRecordHandle">删除数据</span>
            </template>
            <template v-if="type !== 'show'" slot="controls">
              <el-button type="primary" @click="addHandle">新增</el-button>
            </template>
          </FilterTable>
        </div>
      </Anchor>
    </div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeHandler">关闭</el-button>
      <AjaxButton :click="saveHandler" type="primary">保存</AjaxButton>
    </div>

    <!-- 新增选择装饰件 -->
    <BaseDialog :visible.sync="visibleProduct" title="选择装饰件" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <productSelection type="edit" :modifyType="modifyType" :rowData="formData" @close="closeHandler22" @close2="closeHandler2" />
    </BaseDialog>
  </div>
</template>

<script>
// 数据字典/按钮权限
import { dictionary } from '@/utils/dictMixin';
import { authority } from '@/utils/authMixin';
import { notifyAction } from '@/utils';
import { jsonToHump } from '@/utils/index';
import productSelection from './productSelection';
import { excutePartInfo, getProjectList } from '@/api/part/qualityManagement/maintenanceBoutique';
import moment from 'moment';

export default {
  name: '',
  components: {
    productSelection
  },
  mixins: [dictionary, authority],
  props: {
    type: {
      type: String
    },

    formData: {
      type: Object,
      default: () => ({})
    },
    rowData: {
      type: Object,
      default: () => ({})
    },
    baseData: {
      // 客户订单功能页面过来的才有add/edit/show
      type: Array,
      default: () => []
    }
  },

  data() {
    this.saveData = null;

    return {
      labels: this.createAnchorLabels(),
      visibleProduct: false, // 选择产品
      visible5: false,
      // formData: {},
      isChoice: true, // 选中数据false，未选中数据true
      modifyType: true, // 该页面默认为修改
      selectCustomerId: '', // 当前所选customerId
      formList: this.createFormList(),
      serviceItem: this.serviceSource,
      serviceSource: [], // 默认的赋值
      visibleService: false, // 新增服务项目
      columnsWts: this.createTableColums(),
      listWts: [],
      selectedPartTableData: [], // 选中的装饰件列表
      listJp: []
    };
  },
  mounted() {
    // 初始化方法
    this.initialHandle();
    this.createBaseTable();
    this.$tableWts = this.$refs.table1.$refs.pageTable;
  },
  methods: {
    initialHandle() {
      let { baseData } = this;
      if (this.type === 'edit') {
        this.formList.forEach(x => {
          const val = this.formData[x.fieldName];
          if (typeof val === 'undefined') return;
          // 设置回显值
          x.initialValue = val;
          if (x.fieldName === 'isDeleted') {
            console.log(val, '状态');
            this.formList.find(x => x.fieldName === 'isDeleted').initialValue = val === 1 ? true : false;
          }
        });
        // 获取数据
        this.getWtsInfo(this.formData.id);
      }
    },
    createAnchorLabels() {
      return [
        {
          title: '基本信息',
          id: 'row-01'
        },
        {
          title: '装饰件信息',
          id: 'row-02'
        }
      ];
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '装饰项目代码',
          fieldName: 'proCode',
          placeholder: '请输入...',
          rules: [{ required: true, message: '请输入装饰项目代码', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '装饰项目名称',
          fieldName: 'proName',
          placeholder: '请输入...',
          rules: [{ required: true, message: '请输入装饰项目名称', trigger: 'blur' }]
        },

        {
          type: 'INPUT_NUMBER',
          label: '工时费',
          fieldName: 'manhaurFee',
          precision: 2,
          placeholder: '请输入...',
          initialValue: 0,
          rules: [{ required: true, message: '请输入工时费', trigger: 'blur' }]
        },
        {
          type: 'CHECKBOX',
          label: '停用',
          fieldName: 'isDeleted',
          options: {
            trueValue: '1',
            falseValue: '0'
          },
          change: val => {
            const res = val === '0' ? true : false;
            this.formList.find(x => x.fieldName === 'stopDate').disabled = true;
            if (val === '0') {
              this.formList.find(x => x.fieldName === 'stopDate').initialValue = '';
            } else {
              this.formList.find(x => x.fieldName === 'stopDate').initialValue = moment().format('YYYY-MM-DD HH:mm:ss');
            }
          }
        },
        {
          type: 'DATE',
          label: '停用日期',
          fieldName: 'stopDate',
          initialValue: '',
          disabled: true,
          style: { width: '130px' }
        }
      ];
    },
    createTableColums() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '装饰件代码',
          dataIndex: 'partNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '装饰件名称',
          dataIndex: 'partName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '出库单价',
          dataIndex: 'costSalesPrice',
          minWidth: 250,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '数量',
          dataIndex: 'partQty',
          editType: 'number',
          minWidth: 100,
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 0,
          rules: [{ required: true, message: '请输入数量', trigger: 'blur' }],
          editable: true,
          initialValue: 0,
          editRequired: true
        },
        {
          title: '备注',
          dataIndex: 'remark',
          minWidth: 250,
          sorter: true,
          filter: true,
          editable: true,
          editType: 'text',
          filterType: 'input'
        }
      ];
    },

    addHandle() {
      console.log('新增精品项目');
      this.visibleProduct = true;
    },
    // 声明表格组件
    createBaseTable() {
      this.BaseTable1 = this.$refs.table1.$refs.pageTable;
    },
    closeHandler2(val, data) {
      this.visibleProduct = val;
      let productData = data[0];
      console.log('哒哒哒哒哒去吧' + data[0].partName);

      this.$refs.table1.$refs.pageTable.EXECUTE_INSERT(data);
    },
    closeHandler22(val) {
      this.visibleProduct = val;
    },
    formListFill(data, ifNeed = false) {
      // this.selectCustomerId = data['customerId']
      this.formList.forEach(item => {
        if (item.fieldName == 'partNo') {
          item.initialValue = data['partNo'];
        } else if (item.fieldName == 'partName') {
          // 从外层来的叫'price'，从内层窗口组件来的叫'oemDirectivePrice',销售明细页面叫'directivePrice'
          item.initialValue = data['partName'];
        } else {
          item.initialValue = data[item.fieldName];
        }
      });
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    // table行项选中变化
    handlePartTableSelectChange(e) {
      this.selectedPartTableData = e;
    },
    // 删除材料数据
    removeRecordHandle() {
      if (!this.selectedPartTableData.length) return;
      this.$refs.table1.EXECUTE_DELETE(this.selectedPartTableData);
    },

    async getWtsInfo(id) {
      // this.$tableWts.START_LOADING();
      // ajax
      const res = await getProjectList({ id });
      if (res.resultCode === 200) {
        this.listWts = res.data.rows || [];
      }
      // this.$tableWts.STOP_LOADING();
    },
    selectChange(rows) {
      // 选中时触发的函数
      console.log(rows);
      this.selectedRows = rows;
      this.isChoice = this.selectedRows.length > 0 ? false : true;
    },
    closeServiceDialog(val = false, data) {
      // 服务项目dialog关闭
      this.visibleProduct = false;
      console.log('closeServiceDialog', data);
      // 有新增数据
      if (data && data.length > 0) {
        data['birthday'] = this.preDateHandler(data['birthday'], 'YYYY-MM-DD');
        this.$refs.table.$refs.pageTable.EXECUTE_INSERT(data);
        // this.$refs.table.$refs.pageTable.SET_DISABLE_SELECT(data)
        console.log('closeServiceDialog', this.serviceSource);
      }
    },

    async saveHandler() {
      // 保存
      this.saveData = null;
      this.$refs.formPanel.SUBMIT_FORM();
      if (this.saveData != null) {
        let params = _.cloneDeep(this.saveData);
        params.list = _.cloneDeep(this.BaseTable1.dataSource);
        params.ids = this.formData.id;

        let flag = true;
        params.list.map(item => {
          if (item.partQty == '') {
            flag = false;
          }
        });
        if (!flag) {
          notifyAction('数量不能为空！', 'warning');
          return;
        }

        const res = await excutePartInfo(params);
        if (res.resultCode == 200) {
          this.$notify.success({ title: '提示信息', message: '保存成功!' });
          // 需要主页面刷新
          this.closeHandler('refresh');
          this.fetchParams = { ...this.fetchParams };
        }
      }
    },
    // 关闭面板
    closeHandler(type) {
      this.$emit('close', false, type);
    }
  }
};
</script>

<style lang="less" scoped>
.wrapper {
  height: calc(100vh - 135px);
}
</style>
